package com.bw.controller.information;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bw.entity.information.PiProcess;
import com.bw.resp.ResponseResult;
import com.bw.service.information.IPiProcessService;
import com.bw.utils.excel.ExcelUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import net.sf.excelutils.ExcelException;
import net.sf.excelutils.ExcelUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lizhengqian
 * @since 2020-06-16
 */
@RestController
@RequestMapping("/process")
public class PiProcessController {
    @Autowired
    private IPiProcessService piProcessService;

    private final Logger logger= LoggerFactory.getLogger(PiMaterialController.class);

    /*
    * 工序接口
    * */
    @PostMapping("list/{page}/{size}")
    public ResponseResult list(@PathVariable("page") int page, @PathVariable("size") int size,@RequestBody PiProcess piProcess) { //参数json字符串
        logger.info("工序列表查询");
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            PageHelper.startPage(page, size);//开启分页查询
            QueryWrapper queryWrapper = new QueryWrapper();
            if (null != piProcess.getName()) {
                queryWrapper.like("name", "%" + piProcess.getName() + "%");
            }
            queryWrapper.ne("isdelete",0);
            List<PiProcess> piProcesses = piProcessService.list(queryWrapper);//列表查询
            PageInfo pageInfo = new PageInfo(piProcesses);//pagehelper封装好的分页实体类，将数据放进去
            result.setResult(pageInfo);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage("查询失败:" + e.toString());
        }
        logger.info("工序列表查询结束");
        return result;

    }

    @PostMapping("save")
    public ResponseResult save(@RequestBody PiProcess piProcess) { //参数json字符串
        logger.info("工序添加");
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            piProcessService.saveOrUpdate(piProcess);
            result.setMessage("保存成功");
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage("保存失败:" + e.toString());
        }
        logger.info("工序添加结束");
        return result;
    }

    @GetMapping("get/{id}")
    public ResponseResult get(@PathVariable("id") Long id) {
        logger.info("工序根据id进行回显");
        ResponseResult result = ResponseResult.SUCCESS();
        try {
             PiProcess piProcess=piProcessService.getById(id);
             result.setResult(piProcess);
             result.setMessage("修改成功");
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage("修改失败:" + e.toString());
        }
        logger.info("工序根据id进行回显结束");
        return result;
    }

    @DeleteMapping("del/{id}")
    public ResponseResult del(@PathVariable("id") Long id) {
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            PiProcess piProcess= piProcessService.getById(id);

            if(piProcess.getIsdelete()==0){
                piProcess.setIsdelete(1);
            }
            piProcessService.saveOrUpdate(piProcess);
            result.setMessage("删除成功");
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage("删除失败:" + e.toString());
        }
        return result;
    }

    /*@PostMapping("/importExcel")
    public ResponseResult importExcel(MultipartFile file){
        ResponseResult result=ResponseResult.SUCCESS();
        try {
            //获取文件
            String ext=file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."),file.getOriginalFilename().length());
           List<Map> mapList=ExcelUtil.readExcel(ext,file.getInputStream());
           String jsonstr=JSON.toJSONString(mapList);
           List<PiProcess> list=JSON.parseArray(jsonstr,PiProcess.class);
           piProcessService.saveBatch(list);
        }catch (Exception e){
            result.setSuccess(false);
            result.setMessage("上传失败:"+e.toString());
        }
        return result;
    }
*/
    @PostMapping("/importExcel")
    public ResponseResult importExcel(MultipartFile file){
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            String ext = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."), file.getOriginalFilename().length());
            List<Map> mapList = ExcelUtil.readExcel(ext, file.getInputStream());
            String jsonString = JSON.toJSONString(mapList);
            List<PiProcess> list = JSON.parseArray(jsonString, PiProcess.class);
            piProcessService.saveBatch(list);
        }catch (Exception e){
            result.setMessage("导入失败"+e.toString());
            result.setSuccess(false);
        }
        return result;
    }





    @GetMapping("/exportExcel")
    public void exportExcel(HttpServletResponse response) throws IOException, ExcelException {
        List<PiProcess> list = piProcessService.list();

        response.setHeader("Content-Type","application/vnd.ms-excel;charset=UTF-8");
        response.setHeader("Content-Disposition","attachment;filename="+new String("用户数据".getBytes(),"iso-8859-1")+".xls");
        ClassPathResource classPathResource = new ClassPathResource("xls/process.xls");
        InputStream inputStream = classPathResource.getInputStream();//获取excel的模板

        ExcelUtils.addValue("list",list);

        ExcelUtils.export(inputStream,ExcelUtils.getContext(),response.getOutputStream());//第一个参数：模板的流。第三个：输出到哪

    }

}
